package com.baroxtech.testmidisynthesizer;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Switch;

import com.baroxtech.midisynthesizer.MidiSynthesizer;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {
    private MidiSynthesizer synthesizer;
    private SeekBar seekBar;
    private PianoKeyBoard keyBoard;
    private final static int START_KEY = 17;
    private int chan = 0;
    private Properties props;
    private final static String SFNAME = "gs_ptd";
    private final static String TAG = "testfluid";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        seekBar = (SeekBar) findViewById(R.id.activity_play_seek_bar);
        keyBoard = (PianoKeyBoard) findViewById(R.id.keyboard);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                keyBoard.moveToPosition(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        // 配置起始位置
        seekBar.setMax(keyBoard.getMaxMovePosition());

        findViewById(R.id.button_pre_page).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyBoard.showPrevious();
                keyBoard.setPronuncTextDimension(12 * getResources().getDisplayMetrics().scaledDensity);
            }
        });
        findViewById(R.id.button_next_page).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyBoard.showNext();
            }
        });

        keyBoard.setKeyListener(new PianoKeyBoard.KeyListener() {
            @Override
            public void onKeyPressed(Key key) {
                if (synthesizer != null)
                    synthesizer.noteon(chan, key.getKeyCode(), chan == 9 ? 120 : 75);
            }

            @Override
            public void onKeyUp(Key key) {
                if (synthesizer != null) synthesizer.noteoff(chan, key.getKeyCode());
            }

            @Override
            public void currentFirstKeyPosition(int i) {
                if (seekBar.getProgress() != i) {
                    seekBar.setProgress(i);
                }
            }
        });

        keyBoard.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                seekBar.setProgress(START_KEY);
                keyBoard.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
        // 配置发生器的开关
        Switch sw = findViewById(R.id.switch_sound);
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    try {
                        synthesizer = new MidiSynthesizer(getApplicationContext(), SFNAME + ".sf2", 1.0f);
                    } catch (Exception e) {
                        e.printStackTrace();
                        buttonView.setChecked(false);
                    }
                } else {
                    if (synthesizer != null) {
                        synthesizer.close();
                        synthesizer = null;
                    }
                }
            }
        });
        sw.setChecked(true);
        // 配置鼓组开关
        sw = findViewById(R.id.switch_drum);
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (synthesizer != null) {
                    synthesizer.mute(chan);
                }
                chan = isChecked ? 9 : 0;
            }
        });
        sw.setChecked(false);
        // 单独处理配置选择乐器的按钮
        setupSelectProgramBtn();
    }

    private void setupSelectProgramBtn() {
        props = getInstrumentsProperties();

        Button btn = (Button) findViewById(R.id.button_select_program);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 展示弹出框
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                final String[] items = props.stringPropertyNames().toArray(new String[props.size()]);
                builder.setTitle("选择乐器")
                        .setItems(items, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                selectProgram(items[which]);
                            }
                        });
                builder.show();
            }
        });
    }

    private void selectProgram(final String name) {
        if (synthesizer == null) return;
        String val = props.getProperty(name);
        String[] vals = val.split(",");
        synthesizer.selectProgram(0, Integer.parseInt(vals[0]), Integer.parseInt(vals[1]));
        ((Button) findViewById(R.id.button_select_program)).setText(name);
    }

    private Properties getInstrumentsProperties() {
        Properties props = new Properties();
        try {
            props.load(getAssets().open(SFNAME + ".properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return props;
    }
}
